//
//  OrderViewController.m
//  DanaKreditLoan
//
//  Created by ZhengChengFeng on 2024/10/18.
//

#import "OrderViewController.h"
#import "OrderListTableViewCell.h"
#import "EmptyTableViewCell.h"

#define kTabCell           @"kTabCell"
#define kTabNoDataCell     @"kTabNoDataCell"
#define kTabNoNetworkCell  @"kTabNoNetworkCell"

@interface OrderViewController ()

@property (nonatomic) NSInteger defaultSelBtnInteger;

@property (nonatomic) UIScrollView *scrollView;

@property (nonatomic) UIButton *lastBtn;

@property (nonatomic) BOOL isFromMineToStop;

@property (nonatomic) UIImageView *imgV;

@property (nonatomic) NSInteger categoryIndex;

@property (nonatomic) BOOL isOffsetY;

@property (nonatomic) BOOL isNoData,isNetworkError;

@property (nonatomic) NSInteger recorNoNetworkTimes;


@end

@implementation OrderViewController

- (void)viewWillAppear:(BOOL)animated{
    [super viewWillAppear:animated];
    [self.navigationController setNavigationBarHidden:YES animated:animated];
    
    [[AFNetworkReachabilityManager sharedManager] setReachabilityStatusChangeBlock:^(AFNetworkReachabilityStatus status) {
        if (status == 1 || status == 2){
            self.isNetworkError = NO;
            if (self.recorNoNetworkTimes == 1) {
                [self loadData];
            }
            self.recorNoNetworkTimes = 0;
        }
        else{
            self.isNetworkError = YES;
            self.recorNoNetworkTimes = 1;
            [self.data removeAllObjects];
        }
       
        [self.tableView reloadData];
    }];
    
    [[AFNetworkReachabilityManager sharedManager] startMonitoring];
    
    if (self.isFromMineToStop) {
        
        return;
    }
    
    
    self.defaultSelBtnInteger = 0;
    if ([[NSUserDefaults standardUserDefaults] boolForKey:kNeedToRefreshOrderListPage]) {
        [[NSUserDefaults standardUserDefaults] setBool:NO forKey:kNeedToRefreshOrderListPage];
        self.defaultSelBtnInteger = [[NSUserDefaults standardUserDefaults] integerForKey:kRecordBtnNum];
        self.isFromMineToStop = YES;
    }
   
    [self initUI];
    
}


- (void)viewWillDisappear:(BOOL)animated{
    [super viewWillDisappear:animated];
    [self.navigationController setNavigationBarHidden:NO animated:animated];
}


- (void)viewDidLoad {
    self.isTableViewStyleGrouped = YES;
    [super viewDidLoad];
}

- (void)initUI{
    if (self.imgV) {
        [self.imgV removeFromSuperview];
    }
    UIImage *imgIcon = [UIImage imageNamed:@"icon_order1"];
    UIImageView *imgV = [[UIImageView alloc] initWithFrame:CGRectMake(0, 0, kScreenWidth, DimensionBaseIphone6(178))];
    [self.view addSubview:imgV];
    imgV.image = imgIcon;
    self.imgV = imgV;
    self.imgV.userInteractionEnabled = YES;
    
    UILabel *lab = [UILabel createLabel:[UIFont fontWithName:kFuturaMedium size:16] color:kWhiteColor];
    lab.text = ASLocalizedString(@"Loan History");
    lab.textAlignment = 1;
    [self.view addSubview:lab];
    lab.frame = CGRectMake(0, DimensionBaseIphone6(44), kScreenWidth, DimensionBaseIphone6(44));
    
    
    UIView *bottomV = [[UIView alloc] initWithFrame:CGRectMake(0, imgV.bottom - DimensionBaseIphone6(15), kScreenWidth, DimensionBaseIphone6(15))];
    bottomV.backgroundColor = kTableViewBackColor;
    [imgV addSubview:bottomV];
    bottomV.layer.mask = [NSString UIBezierPathWithRect:bottomV.bounds withCorners:UIRectCornerTopLeft | UIRectCornerTopRight withRadiu:CGSizeMake(10, 10)];
    
    UIView *bottomV2 = [[UIView alloc] initWithFrame:CGRectMake(0, bottomV.bottom - DimensionBaseIphone6(5), kScreenWidth, DimensionBaseIphone6(5))];
    bottomV2.backgroundColor = kTableViewBackColor;
    [imgV addSubview:bottomV2];
    
    [self initScrollerView];
    [self initSubView];
    
    self.tableView.frame = CGRectMake(0, imgV.bottom, kScreenWidth, kScreenHeight - imgV.bottom);
    
    
    
    
    self.tableView.tableFooterView = [[UIView alloc] initWithFrame:CGRectMake(0, 0, kScreenWidth, 40)];
    
    [self.tableView registerClass:[EmptyTableViewCell class] forCellReuseIdentifier:kTabNoDataCell];
    [self.tableView registerClass:[EmptyTableViewCell class] forCellReuseIdentifier:kTabNoNetworkCell];
    [self.tableView registerClass:[OrderListTableViewCell class] forCellReuseIdentifier:kTabCell];
    
    [self.tableView reloadData];
}

- (void)initScrollerView{
    if (self.scrollView) {
        [self.scrollView removeFromSuperview];
    }
    UIScrollView *scrollView = [[UIScrollView alloc] initWithFrame:CGRectMake(0, DimensionBaseIphone6(98), kScreenWidth, 53)];
    scrollView.scrollsToTop = NO;
    scrollView.showsHorizontalScrollIndicator = NO;
    scrollView.showsVerticalScrollIndicator = NO;
    [self.imgV addSubview:scrollView];
    self.scrollView = scrollView;
    self.scrollView.backgroundColor = [UIColor clearColor];
}

- (void)initSubView{
    NSArray *titleArr = @[ASLocalizedString(@"All"),ASLocalizedString(@"Applying"),ASLocalizedString(@"Repayment"),ASLocalizedString(@"Finish")];
    NSArray *imgArr = @[@"icon_order5",@"icon_order6",@"icon_order7",@"icon_order8"];
    
    CGFloat fixL = 15;
    CGFloat fixM = 8;
    CGFloat itemBtnWidth = 110;
    
    for (int i =0; i<titleArr.count; i++) {
        UIButton *btn = [[UIButton alloc] init];
        btn.tag = i;
        btn.frame = CGRectMake(i*itemBtnWidth + fixL + fixM*i, 0,itemBtnWidth, 48);
        [self.scrollView addSubview:btn];
        
        [btn addTarget:self action:@selector(clickBtn:) forControlEvents:UIControlEventTouchUpInside];
        
        [btn setImage:[UIImage imageNamed:@"icon_order3"] forState:UIControlStateNormal];
        [btn setImage:[UIImage imageNamed:@"icon_order3"] forState:UIControlStateHighlighted];
        [btn setImage:[UIImage imageNamed:@"icon_order2"] forState:UIControlStateSelected];
        
        if (i == self.defaultSelBtnInteger) {
            btn.selected = YES;
            self.lastBtn = btn;
            [self clickBtn:btn];
        }
        
        UILabel *lab  =[UILabel createLabel:[UIFont fontWithName:kFutura size:14] color:kBlackColor];
        [btn addSubview:lab];
        lab.text = titleArr[i];
        lab.frame = CGRectMake(10, 0, 100, 48);
        
        UIImageView *icon = [[UIImageView alloc] initWithFrame:CGRectMake(btn.width - 10 -25, (48-25)/2, 25, 25)];
        [btn addSubview:icon];
        icon.image = [UIImage imageNamed:imgArr[i]];
        
    }
    
    self.scrollView.contentSize = CGSizeMake(titleArr.count *itemBtnWidth + fixL + (titleArr.count - 1)*fixM + fixL, self.scrollView.frame.size.height);
}

- (void)clickBtn:(UIButton *)btn{
    
    [self.lastBtn setImage:[UIImage imageNamed:@"icon_order3"] forState:UIControlStateHighlighted];
    self.lastBtn.height = 48;
    self.lastBtn.selected = NO;
    
    btn.selected = YES;
    
    self.lastBtn = btn;
    
    self.lastBtn.height = 53;
    
    [self.lastBtn setImage:[UIImage imageNamed:@"icon_order2"] forState:UIControlStateHighlighted];
    
    self.categoryIndex = btn.tag;
    [self loadData];
    
    if (btn.tag == 3) {
        [self.scrollView setContentOffset:CGPointMake(110-8, 0)];
    }
    else{
        [self.scrollView setContentOffset:CGPointMake(0, 0)];
    }
    
    
}

- (void)loadData{
    
    if (![[CurrentUser mine] hasLogged] || self.isNetworkError) {
        [BoxLoadingHelper hideBoxLoadingFromView:self.view];
        [BoxLoadingHelper hideBoxLoading];
        return;
    }
    
    NSString *str = @"";
    if (self.categoryIndex == 0) {
        str = @"4";
    }
    else if (self.categoryIndex == 1) {
        str = @"7";
    }
    else if (self.categoryIndex == 2) {
        str = @"6";
    }
    else if (self.categoryIndex == 3) {
        str = @"5";
    }
    NSMutableDictionary *muDic = @{
        @"hurried":esString(str),
        @"stampede":@"1",
        @"anyway":@"50",
    }.mutableCopy;
    
    [BoxLoadingHelper showBoxLoadingWithMessage:@"" onView:self.view withOriginY:0];
    [HttpNetHelper postNetworkHelperForPath:kOrderListUrl parameter:muDic onCompleteSuccess:^(NSDictionary * _Nonnull responseDic) {
        [BoxLoadingHelper hideBoxLoadingFromView:self.view];
        [BoxLoadingHelper hideBoxLoading];
        self.isFromMineToStop = NO;
        if ([responseDic[@"pineapples"] integerValue] != kSuccessCode) {
            [BoxLoadingHelper showBoxWithMessage:esString(responseDic[@"shin"])];
            return;
        }
        
        [self.data removeAllObjects];
        
        NSDictionary *dic = responseDic[@"clip"];
        
        NSArray *pinAry = dic[@"continuing"];
        
        self.data = [OrderListModel mj_objectArrayWithKeyValuesArray:pinAry];
        
        if (self.data.count == 0) {
            self.isNoData = YES;
        } else {
            self.isNoData = NO;
        }
        
        [self.tableView reloadData];
        
    } onCompleteFailur:^(NSError * _Nonnull error) {
        self.isFromMineToStop = NO;
        [BoxLoadingHelper hideBoxLoadingFromView:self.view];
        [BoxLoadingHelper hideBoxLoading];
    } withIsForm:YES];
    
}

- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section{
    return 1;
}

- (NSInteger)numberOfSectionsInTableView:(UITableView *)tableView{
    if (self.isNoData) {
        return 1;
    }
    else if (self.isNetworkError) {
        return 1;
    }
    return self.data.count;
}

- (CGFloat)tableView:(UITableView *)tableView heightForRowAtIndexPath:(NSIndexPath *)indexPath{

    UIImage *img = [UIImage imageNamed:@"icon_empty"];
    if (self.isNoData) {
        return 140 + img.size.height + 5 + 5 +36 + 20 + 25;
    }
    else if (self.isNetworkError) {
        return 140 + img.size.height + 5 + 5 +36 + 20 + 60;
    }
    return [OrderListTableViewCell getCellHeight:self.data[indexPath.section]];
}

- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath{
    if (self.isNoData) {
        EmptyTableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:kTabNoDataCell];
        cell.selectionStyle = UITableViewCellSelectionStyleNone;
        cell.isNetError = NO;
        cell.clickBtnBlock = ^{
            [self goApply];
        };
        return cell;
    }
    else if (self.isNetworkError) {
        EmptyTableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:kTabNoNetworkCell];
        cell.selectionStyle = UITableViewCellSelectionStyleNone;
        cell.isNetError = YES;
        cell.clickBtnBlock = ^{
            [[DKCore sharedDKCore] showNetErrorAlertView];
        };
        return cell;
    }
    OrderListTableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:kTabCell];
    cell.selectionStyle = UITableViewCellSelectionStyleNone;
    if (self.data.count > 0) {
        cell.model = self.data[indexPath.section];
    }
    return cell;
}

- (void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath{
    [tableView deselectRowAtIndexPath:indexPath animated:YES];
    
    if (self.isNetworkError || self.data.count == 0) {
        return;
    }
    
    OrderListModel *model = self.data[indexPath.section];
    
    
    [[DKCore sharedDKCore] jumpToControllerWithUrlString:esString(model.che)];
    
}

- (void)goApply{
    [self.tabBarController setSelectedIndex:0];
    [[NSNotificationCenter defaultCenter] postNotificationName:kNotificationTabBarNum object:nil userInfo:@{@"index":@"1"}];
}

- (UIView *)tableView:(UITableView *)tableView viewForFooterInSection:(NSInteger)section{
    UIView *footV = [[UIView alloc] init];
    
    if (self.isNetworkError || self.data.count == 0) {
        return footV;
    }
    
    OrderListModel *mm = self.data[section];
    
    UIButton *tipBtn = [[UIButton alloc] initWithFrame:CGRectMake(20, 0, kScreenWidth - 40, 36)];
    [footV addSubview:tipBtn];
    tipBtn.titleLabel.font = [UIFont fontWithName:kFutura size:12];
    [tipBtn setTitleColor:[UIColor colorWithHexString:@"#FF7171"] forState:UIControlStateNormal];
    [tipBtn setTitleColor:[UIColor colorWithHexString:@"#FF7171"] forState:UIControlStateSelected];
    [tipBtn setTitleColor:[UIColor colorWithHexString:@"#FF7171"] forState:UIControlStateHighlighted];
    [tipBtn setTitle:esString(mm.overDueDayContent) forState:UIControlStateNormal];
    [tipBtn setTitle:esString(mm.overDueDayContent) forState:UIControlStateSelected];
    [tipBtn setTitle:esString(mm.overDueDayContent) forState:UIControlStateHighlighted];
    [tipBtn setImage:[UIImage imageNamed:@"icon_order4"] forState:UIControlStateNormal];
    [tipBtn setImage:[UIImage imageNamed:@"icon_order4"] forState:UIControlStateSelected];
    [tipBtn setImage:[UIImage imageNamed:@"icon_order4"] forState:UIControlStateHighlighted];
    tipBtn.contentHorizontalAlignment = UIControlContentHorizontalAlignmentLeft;
    
    
    if (!PMStringIsEmpty(mm.overDueDayContent)) {
        tipBtn.hidden = NO;
    } else {
        tipBtn.hidden = YES;
    }
    
    return footV;
}

- (CGFloat)tableView:(UITableView *)tableView heightForFooterInSection:(NSInteger)section{
    if (self.isNetworkError || self.data.count == 0) {
        return 0.0001f;
    }
    OrderListModel *mm = self.data[section];
    if (!PMStringIsEmpty(mm.overDueDayContent)) {
        return 36;
    }
    return 12;
}

- (UIView *)tableView:(UITableView *)tableView viewForHeaderInSection:(NSInteger)section{
    UIView *secV = [[UIView alloc] init];
    return secV;
}

- (CGFloat)tableView:(UITableView *)tableView heightForHeaderInSection:(NSInteger)section{
    return 0.0001f;
}

/*
#pragma mark - Navigation

// In a storyboard-based application, you will often want to do a little preparation before navigation
- (void)prepareForSegue:(UIStoryboardSegue *)segue sender:(id)sender {
    // Get the new view controller using [segue destinationViewController].
    // Pass the selected object to the new view controller.
}
*/

- (void)scrollViewDidScroll:(UIScrollView *)scrollView{
    
    if (self.isNetworkError) {
        return;
    }

    CGFloat offset_Y = scrollView.contentOffset.y;
   
    
    if (offset_Y < 0) {
        if (offset_Y < - kNavigationBarHeight) {
            self.isOffsetY = YES;
        }
        
    }else{
        
        if (self.isOffsetY) {
            self.isOffsetY = NO;
            [self loadData];
        }
        
    }
}

@end













